package umg;

import java.util.Random;

import umg.gui.GUI;
import umg.util.HTMLStreamUtils;
import umg.util.PropertyManager;

public class ChatReaderThread extends Thread
{
	private int server = 0;
	GUI gui;
	static String[] lastLines;

	public ChatReaderThread(final int server_index, GUI gui)
	{
		super();
		this.server = server_index;
		this.gui = gui;
	}

	@Override
	public void run()
	{
		this.setPriority(PropertyManager.getThreadPriorityInt() - 1);// chats
		// run
		// at a
		// slightly
		// lower
		// priority.
		this.setName(PropertyManager.getWebadminURLNames()[server] + Messages.getString("ChatReaderThread.0"));
		// GUI.logToStatus("\""+this.getName()+"\" is starting after a random wait of "+startupSleepms+"ms with priority of "+this.getPriority());
		try
		{
			Random randomGenerator = new Random();
			int startupSleepms = randomGenerator.nextInt(5 * 1000);
			// System.out.println("\""+this.getName()+"\" is starting after a random wait of "+startupSleepms+"ms with priority of "+this.getPriority());
			// GUI.logToStatus("\""+this.getName()+"\" is starting after a random wait of "+startupSleepms+"ms with priority of "+this.getPriority());
			sleep(startupSleepms);
			GUI.logToStatus(Messages.getString("ChatReaderThread.1") + this.getName() + Messages.getString("ChatReaderThread.2") + Constants.SPACE_STR + this.getPriority());
		}
		catch (InterruptedException e1)
		{
			e1.printStackTrace();
		}
		if (PropertyManager.isDebug()) System.out.println(Messages.getString("ChatReaderThread.3") + this.getName() + Messages.getString("ChatReaderThread.4") + Constants.SPACE_STR + this.getPriority());

		while (true)
		{
			if (GUI.databaseQueryModeMenuItem != null && GUI.databaseQueryModeMenuItem.isSelected() == false)
			{
				try
				{
					if (PropertyManager.getChat_enabled().equalsIgnoreCase(Messages.getString("ChatReaderThread.5")))
					{
						updateChatLogs(System.currentTimeMillis());
					}
				}// try
				catch (Exception e)
				{
					System.out.println(Messages.getString("ChatReaderThread.6") + e.getMessage() + Messages.getString("ChatReaderThread.7") + server + Messages.getString("ChatReaderThread.8")); //$NON-NLS-3$
					e.printStackTrace();
				}
			}
			try
			{
				sleep(Integer.parseInt(PropertyManager.getGrab_interval()) * 1000 / 3);
			}
			catch (InterruptedException e)
			{
			}
		}// while
	}

	Boolean isGrabInProgress = Boolean.FALSE;
	private static final Object syncObject = new Object();

	public void updateChatLogs(long scheduledExecutionTime)
	{
		long startTime = System.currentTimeMillis();
		synchronized (syncObject)
		{
			if (isGrabInProgress == false)
			{
				isGrabInProgress = Boolean.TRUE;
			}
			else
			{
				System.out.println(Messages.getString("ChatReaderThread.9"));
				return;
			}
		}

		try
		{
			String[] lines;
			String currentLastLine = Messages.getString("ChatReaderThread.10");
			// int vscroll_pos=0;
			boolean newlinesfound = false;
			for (int url_number = 0; url_number < PropertyManager.getWebadminURLs().length; url_number++)
			{
				newlinesfound = false;
				if (PropertyManager.isDebug()) System.out.println(Messages.getString("ChatReaderThread.11") + Constants.SPACE_STR + url_number);
				// get chat html, last line is at the bottom
				lines = HTMLStreamUtils.getChatLinesHTML(url_number, scheduledExecutionTime);
				if (lines == null || (lines != null && lines.length == 0)) continue;// no lines or error
				if (PropertyManager.isDebug()) System.out.println(Messages.getString("ChatReaderThread.12") + lines.length + Messages.getString("ChatReaderThread.13") + Constants.SPACE_STR + url_number);
				if (lines[lines.length - 1].endsWith(Messages.getString("ChatReaderThread.14")))
				{
					lines[lines.length - 1] = lines[lines.length - 1].substring(0, lines[lines.length - 1].length() - 4);// remove
					// the
					// pesky
					// <br>
					// on
					// the
					// last
					// line
				}
				currentLastLine = lines[lines.length - 1];// last
				if (lastLines == null)
				{
					lastLines = new String[PropertyManager.getWebadminURLs().length];
				}
				if (lastLines[url_number] == null)
				{// first chat line for this url#
					lastLines[url_number] = currentLastLine;
					newlinesfound = true;
				}
				else
				{// check if there have been any new chat lines by comparing
					// last lines
					if (lastLines[url_number].equals(currentLastLine) || lines[0].equals(Messages.getString("ChatReaderThread.15")) || (lastLines[url_number].startsWith(Messages.getString("ChatReaderThread.16")) && currentLastLine.startsWith(Messages.getString("ChatReaderThread.16")))) //$NON-NLS-3$
					{
						// no new lines or empty, no change
						// or, game has ended multiple times bug. (the time
						// changes)
						if (PropertyManager.isDebug()) System.out.println(Messages.getString("ChatReaderThread.18") + Constants.SPACE_STR + url_number);
					}
					else
					{// add all the new lines since the previous last line
						newlinesfound = true;
						// find the index of the last line in lines[]
						int i;
						for (i = 0; i < lines.length; i++)
						{
							if (lines[i].equals(lastLines[url_number]))
							{
								break;
							}
						}// for

						if (i < lines.length)
						{// found, add all the new lines from i+1 to the end,
							// i.e
							String[] newerLines = new String[lines.length - (i + 1)];
							i++;
							for (int j = 0; i < lines.length; j++)
							{
								newerLines[j] = lines[i++];
							}
							lines = newerLines;// only interested int he newer
							// lines
						}
						else
						{// add all lines
						}
					}// else, add new lines
				}// else, check for new lines
				if (newlinesfound == true)
				{
					if (PropertyManager.isDebug()) System.out.println(Messages.getString("ChatReaderThread.19") + lines.length + Messages.getString("ChatReaderThread.20") + Constants.SPACE_STR + url_number);
					// //////////////processLines//////////////////
					StringBuilder stringBuilder = new StringBuilder();
					String teamcolor = Messages.getString("ChatReaderThread.10");
					String playerName = Messages.getString("ChatReaderThread.10");
					// reverse the array
					for (int i = lines.length - 1; i >= 0; i--)
					{
						// chatLogArray[i]=chatLogArray[i].trim();
						if (lines[i].startsWith(Messages.getString("ChatReaderThread.23")))
						{// webadmin
							stringBuilder.append(Messages.getString("ChatReaderThread.24"));
							stringBuilder.append(lines[i]);
							stringBuilder.append(Messages.getString("ChatReaderThread.25"));
							stringBuilder.append(Messages.getString("ChatReaderThread.26"));
						}
						else if (lines[i].startsWith(Messages.getString("ChatReaderThread.27")))
						{// spec teamspeak
							stringBuilder.append(Messages.getString("ChatReaderThread.28"));// light
							// green
							stringBuilder.append(lines[i]);
							stringBuilder.append(Messages.getString("ChatReaderThread.25"));
							stringBuilder.append(Messages.getString("ChatReaderThread.26"));
						}
						else
						{// normal player chat
							// get color from the team
							teamcolor = Messages.getString("ChatReaderThread.10");
							playerName = Messages.getString("ChatReaderThread.10");
							int playerNameEndIndex = lines[i].indexOf(Messages.getString("ChatReaderThread.33"));
							if (playerNameEndIndex == -1)// not found
							{
								// must be webadmin
								if (!lines[i].startsWith(Messages.getString("ChatReaderThread.16")))
								{
									lines[i] = Messages.getString("ChatReaderThread.35") + Constants.SPACE_STR + lines[i];
								}
								teamcolor = Constants.SPEC_STR;
							}
							else
							{
								// try and get the playername
								try
								{
									playerName = lines[i].substring(0, playerNameEndIndex);
								}
								catch (Exception ignore)
								{
									ignore.printStackTrace();
								}
							}
							for (int v = 0; v < PropertyManager.getWebadminURLs().length && teamcolor.length() == 0; v++)
							{
								// TableModel
								// model=gui.matchSnapShotTables[v].getModel();
								// update to use the cached model
								Object[][] serverPlayerData = GUI.playerData[v];
								if (serverPlayerData.length <= 1) break;
								for (int j = 0; j < serverPlayerData.length && teamcolor.length() == 0; j++)
								{// col 0 is name, 4 is team
									if (serverPlayerData[j][0] != null && ((String) serverPlayerData[j][0]).equals(playerName))
									{
										teamcolor = (String) serverPlayerData[j][5];
										break;
									}
								}
							}// search through all player lists
								// return colors
							if (teamcolor.equalsIgnoreCase(Messages.getString("ChatReaderThread.36"))) teamcolor = Messages.getString("ChatReaderThread.37");
							if (teamcolor.equalsIgnoreCase(Messages.getString("ChatReaderThread.38"))) teamcolor = Messages.getString("ChatReaderThread.39");
							if (teamcolor.equalsIgnoreCase(Messages.getString("ChatReaderThread.40"))) teamcolor = Messages.getString("ChatReaderThread.41");
							if (teamcolor.equalsIgnoreCase(Messages.getString("ChatReaderThread.10"))) teamcolor = Messages.getString("ChatReaderThread.43");
							// add team color html
							stringBuilder.append(Messages.getString("ChatReaderThread.44") + teamcolor + Messages.getString("ChatReaderThread.45"));
							stringBuilder.append(lines[i]);
							stringBuilder.append(Messages.getString("ChatReaderThread.25"));
							stringBuilder.append(Messages.getString("ChatReaderThread.26"));
						}// normal player chat
					}// for all lines
						// convert it all into one long string containing <br>.
					String oldlog = gui.logs[url_number];
					if (oldlog == null) oldlog = Messages.getString("ChatReaderThread.10");
					gui.logs[url_number] = stringBuilder.toString() + gui.logs[url_number];// add
					// to
					// the
					// end
					// of
					// the
					// previous
					// logs
					lastLines[url_number] = currentLastLine;// new last line
					gui.logsJEditorPane[url_number].setText(gui.logs[url_number]);
					// if(gui.isShowing()) gui.repaint();
				}
			}// for
		}
		catch (Exception e)
		{

		}
		finally
		{
			long endTime = System.currentTimeMillis();
			if (PropertyManager.isDebug()) System.out.println(Messages.getString("ChatReaderThread.49") + (endTime - startTime) + Messages.getString("ChatReaderThread.50"));
			isGrabInProgress = Boolean.FALSE;
		}
	}

	public void setServer(int server)
	{
		this.server = server;
	}

	public int getServer()
	{
		return server;
	}
}
